package com.sso.controller;

import com.alibaba.fastjson.JSON;
import com.common.entity.User;
import com.common.untils.CommonResult;
import com.sso.openFeign.PermissionFeign;
import com.sso.token.UsernamePasswordToken;
import com.sso.vo.Loginvo;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @create 2022-08-29
 */
@RestController
@RequestMapping("sso")
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PermissionFeign permissionFeign;
    @RequestMapping("login")
    public CommonResult login(@RequestBody Loginvo loginvo){

        Subject subject = SecurityUtils.getSubject();
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(loginvo.getUsername(),loginvo.getPassword());
            //交于shiro自定义realm中的认证方法
            subject.login(token);
            //生成一个唯一token 保存到redis中
            String uuid = UUID.randomUUID().toString().replace("-","");
            //登陆成功后的用户信息
            User user = (User) subject.getPrincipal();
            //根据用户id查询用户具有的权限
            List<String> permission = permissionFeign.findPermissionByUserid(user.getUserId());
            //value中应该包含用户信息    以及用户具有的权限
            Map<String,Object> map=new HashMap<>();
            map.put("user",user);
            map.put("permission",permission);
            map.put("token",uuid);
            redisTemplate.opsForValue().set(uuid, JSON.toJSONString(map),24, TimeUnit.HOURS);
            return new CommonResult(2000,"登陆成功",map);
        }catch (Exception e){
            e.printStackTrace();
            return  new CommonResult(5000,"认证失败",null);
        }
    }

}
